const express = require('express');
const User = require('../db/User.js');
const generateNumericId = require('../public/generateNumericId.js');
const jwt = require('jsonwebtoken');
const { SECRET } = require('../config/config.js');
const bcryptjs = require('bcryptjs');



const router = express.Router();

// 用户注册
router.post('/register', async (req, res) => {
    console.log(req.body);
    const { username, password } = req.body;
    const existingUser = await User.findOne({ username });
    if (existingUser) {
        // 如果用户名已存在，返回 JSON 格式的错误信息
        return res.json({
            code: "1001",
            msg: '用户名已存在，请选择其他用户名'
        });
    }
    const id = generateNumericId();
    const user = await User.create({
        userId: id,
        username: username,
        password: password
    })
    //用userID生成token
    const token = jwt.sign({ id }, SECRET, { expiresIn: '1h' });
    res.json({
        code: '0000',
        msg: '注册成功',
        userId: id + '',
        userToken: token
    });
});

//用户登录
router.post('/login', (req, res) => {
    console.log(req.body);
    const { userId, password } = req.body;
    User.findOne({ userId }).then((result) => {
        console.log(result);
        if (!result) return res.json({
            code: 1002,
            msg: "账号不存在"
        });
        if (!bcryptjs.compareSync(password, result.password))
            return res.json({
                code: 1003,
                msg: "密码错误"
            });
        //用userID生成token
        const token = jwt.sign({ userId }, SECRET, { expiresIn: '1h' });
        res.json({
            code: '0000',
            msg: '登录成功',
            userToken: token,
            username: result.username
        });
    })
})

module.exports = router;